import '../public/index'
import url from '../data/url'
import request from '../data/request'
import { tableConfig, header} from '../data/config'
import store from 'store'

const base               = url.base,
      getPOSKeyboardBind = request.getTerminal,
      getDeveloperList   = request.getDeveloperList,
      getReceiving       = request.getReceiving,
      getBuildingList    = request.getBuildingList,
      unbindTerminal     = request.unbindTerminal,
      getPact            = request.getPact,
      bindTerminal       = request.bindTerminal;

let table,
    storeData,
    devList

// 初始化表格
table = $('#table').bootstrapTable($.extend({}, tableConfig, {
  url: base + getPOSKeyboardBind,
  queryParams: function (params) {
    return $.extend({
      currentPage: params.pageNumber,
      pageSize: params.pageSize,
    },$('#searchForm').serializeObject())
  },
  columns: [
    {
      field: 'identifier',
      title: '终端号',
      valign: 'middle'
    }, {
      field: 'typeName',
      title: '终端类型',
      valign: 'middle'
    }, {
      field: 'dName',
      title: '开发商',
      valign: 'middle'
    }, {
      field: 'houseName',
      title: '楼盘名称',
      valign: 'middle'
    }, {
      field: 'receivablesPeopleName',
      title: '收款单位',
      valign: 'middle'
    }, {
      field: 'payChannelName',
      title: '支付渠道',
      valign: 'middle'
    }, {
      field: 'statusName',
      title: '状态',
      valign: 'middle',
      width: '80px'
    }, {
      field: 'status',
      valign: 'middle',
      align: 'center',
      width: '170px',
      title: '操作',
      formatter: function (index, row) {

        String(index)

        switch (index) {
          case '2':
            return `<div class="btn-group">
                      <button type="button" data-identifier="${ row.identifier }" data-cusId="${ row.cusId }" class="btn btn-default btn-unbind">解绑</button>                  
                      <button type="button" data-id="${ row.id }" class="btn btn-default btn-modify">修改</button>                                  
                    </div>`
            break
          case '1':
            return `<div class="btn-group">
                      <button type="button" data-id="${ row.id }" data-cusId="${ row.cusId }" data-identifier="${ row.identifier }" data-typeName="${ row.typeName }" class="btn btn-default btn-bind">分配</button>                                          
                    </div>`
            break
        }
      }
    }]
}));

// 点击列表的时候传递数据到全局变量
table.on('click-row.bs.table', (e, data, el) => {
  storeData = data
});

//初始化开发商
getDev();

function getDev() {

  $.ajax({
    headers: header,
    url: base + getDeveloperList
  })
    .done(function (res) {
      console.log(res)

      let code = res.code;

      if (code == 0) {
        console.log("获取开发商成功")
        devList = res;
        let project = $('#developersId'),
          html = '<option value="">请选择</option>',
          i = 0,
          data = res.object,
          len = data.length;

        for (; i < len; i++) {
          html += `<option value="${ data[i].enterInfo ? data[i].enterInfo.idStr : '' }">${ data[i].enterInfo ? data[i].enterInfo.enterpriseName : ''  }</option>`
        }

        project.html(html)
        project.selectize()
      } else {
        $('#devId').addClass('form-control')

        layer.msg('获取开发商失败', {
          icon: 5
        })
      }
    })
    .fail(function (res) {
      console.log(res)
      console.log("error")

    })
    .always(function (res) {
      console.log("complete")
    })
}

function getReceivablesPeople() {

  $.ajax({
    headers: header,
    url: base + getReceiving
  })
    .done(function (res) {
      console.log(res)
      console.log("获取收款方成功")

      let project = $('#receivablesPeopleId'),
          html = '<option value="">请选择</option>',
          i = 0,
          data = res.object,
          len = data.length;

      for (; i < len; i++) {
        html += `<option value="${ data[i].enterInfo.id }">${ data[i].enterInfo.enterpriseName  }</option>`
      }

      project.html(html)
      console.log(html);

    })
    .fail(function (res) {
      console.log(res)
      console.log("error")

    })
    .always(function (res) {
      console.log("complete")
    })
}

function getBuild(developersId) {
  let data;

  if (developersId) {
    data = {developersId: developersId}
  } else {
    data = {}
  }

  $.ajax({
    headers: header,
    type: 'GET',
    url: base + getBuildingList,
    data: data
  })
    .done(function (res) {
      console.log(res)

      let code = res.code,
        project = $('#dropertyIdBind');

      if (code == 0) {
        console.log("获取楼盘成功")

        let html = '<option value="">请选择</option>',
          i = 0,
          data = res.object,
          len = data.length;

        for (; i < len; i++) {
          html += `<option value="${ data[i].idStr }">${ data[i].propertyName }</option>`
        }

        project.html(html)
      } else {
        project.html('<option value="">请选择</option>')
        layer.msg('获取楼盘失败', {
          icon: 5
        })
      }
    })
    .fail(function (res) {
      console.log(res)
      console.log("error")
      let project = $('#buildingId')
      project.html('<option value="">请选择</option>')

    })
    .always(function (res) {
      console.log("complete")
    })
}

function getPactList() {

  $.ajax({
    headers: header,
    url: base + getPact
  })
    .done(function (res) {
      console.log(res)

        console.log("获取合同成功")

        let project = $('#pact'),
            html    = '',
            i       = 0,
            data    = res.object,
            len     = data.length;

        for (; i < len; i++) {
          html += `<div class="checkbox">
                      <label>
                       <input name="contractId" type="checkbox" value="${data[i].idStr}">
                        ${data[i].contractName}
                     </label>
                  </div>`;
        }
        project.html(html)

    })
    .fail(function (res) {
      console.log(res)
      console.log("error")

    })
    .always(function (res) {
      console.log("complete")
    })
}

// 搜索
$('#search-btn').on('click', (e) => {
  e.preventDefault();

  table.bootstrapTable('refresh', {
    query: $.extend({
      currentPage : 1,
    }, $('#searchForm').serializeObject())
  })
});

// 状态搜索
$("input[name = 'status']").on('change', (e) => {
  e.preventDefault();

  table.bootstrapTable('refresh', {
    query: $.extend({
      currentPage : 1,
    }, $('#searchForm').serializeObject())
  })
});

// 监控开关搜索
$("input[name = 'type']").on('change', (e) => {
  e.preventDefault();

  table.bootstrapTable('refresh', {
    query: $.extend({
      currentPage : 1,
    }, $('#searchForm').serializeObject())
  })
});

// 解绑
$(document).on('click', '#table .btn-unbind', (e) => {
  e.preventDefault()

  console.log('解绑')

  let identifier = $(e.target).attr('data-identifier'),
    cusId = $(e.target).attr('data-cusId'),
    data = {
      identifier: identifier,
      cusId: cusId
    };

  bootbox.confirm({
    title: '提示',
    message: `<div>
                <h3 style="margin:.75em 0">是否解绑？</h3>
              </div>`,
    buttons: {
      cancel: {
        label: '取消'
      },
      confirm: {
        label: '解绑'
      }
    },
    callback: (result) => {

      if (!result) {
        return
      }

      let loading_modal = layer.msg('提交中...', {
        icon: 16,
        time: 0
      })

      $.ajax({
        headers: header,
        url: base + unbindTerminal,
        type: 'POST',
        data: data
      })
        .done(function (res) {
          console.log(res)

          if (res.code == 0) {

            layer.msg('解绑成功', {
              icon: 6
            })

            table.bootstrapTable('refresh')

          } else {
            layer.msg('解绑失败', {
              icon: 5
            })
          }

        })
        .fail(function (res) {
          console.log(res)

          layer.msg('解绑失败', {
            icon: 5
          })

        })
        .always(function (res) {

          console.log("complete")

          layer.close(loading_modal)
        })
    }
  })
});

// 分配
$(document).on('click', '#table .btn-bind', (e) => {
  e.preventDefault()

  console.log('分配')

  let id         = $(e.target).attr('data-id'),
      res        = devList,
      identifier = $(e.target).attr('data-identifier'),
      typeName   = $(e.target).attr('data-typeName'),
      cusId      = $(e.target).attr('data-cusId'),
      html       = '<option value="">请选择</option>',
      i          = 0,
      data       = res.object,
      len        = data.length,
      messageHtml;

  for (; i < len; i++) {
    html += `<option value="${ data[i].enterInfo.idStr }">${ data[i].enterInfo.enterpriseName  }</option>`
  }
  
  // 0 一体机
  // 1 平板
  // 2 post
  let type = 0

  switch (typeName){
    case '一体机':
      messageHtml = `<div>
                      <form id="bindForm" action="">
                        <div class="form-group">
                          <label for="">识别号</label>
                          <input name="identifier" value="${identifier ? identifier : ''}" class="form-control" readonly type="text">
                        </div>
                        <div class="form-group">
                          <label for="">类型</label>
                          <input name="" value="${typeName ? typeName : ''}" class="form-control" disabled type="text">
                        </div>
                        <div class="form-group">
                          <label for="">开发商</label>
                          <select id="developersIdBind" name="developersId" class="form-control" type="text">${ html }</select>
                        </div>
                        <div class="form-group">
                          <label for="">楼盘名称</label>
                          <select id="dropertyIdBind" name="dropertyId" class="form-control" type="text"></select>
                        </div>
                      </form>
                    </div>`
      break
    case '平板':
      type = 1
      messageHtml = `<div>
                      <form id="bindForm" action="">
                        <div class="form-group">
                          <label for="">识别号</label>
                          <input name="identifier" value="${identifier ? identifier : ''}" class="form-control" readonly type="text">
                        </div>
                        <div class="form-group">
                          <label for="">类型</label>
                          <input name="" value="${typeName ? typeName : ''}" class="form-control" disabled type="text">
                        </div>
                        <div class="form-group">
                          <label for="">开发商</label>
                          <select id="developersIdBind" name="developersId" class="form-control" type="text">${ html }</select>
                        </div>
                        <div class="form-group">
                          <label for="">楼盘名称</label>
                          <select id="dropertyIdBind" name="dropertyId" class="form-control" type="text"></select>
                        </div>
                        <div id="pact" class="form-group"></div>
                      </form>
                    </div>`
      break
    case 'pos':
    case 'POST':
    case 'pos机':
    case 'POS机':
      type = 2
      messageHtml = `<div>
                      <form id="bindForm" action="">
                        <div class="form-group">
                          <label for="">识别号</label>
                          <input name="identifier" value="${identifier ? identifier : ''}" class="form-control" readonly type="text">
                        </div>
                        <div class="form-group">
                          <label for="">类型</label>
                          <input name="" value="${typeName ? typeName : ''}" class="form-control" disabled type="text">
                        </div>
                        <div class="form-group">
                          <label for="">收款方</label>
                          <select id="receivablesPeopleId" name="receivablesPeopleId" class="form-control" type="text"></select>
                        </div>
                        <div class="form-group">
                          <label for="">开发商</label>
                          <select id="developersIdBind" name="developersId" class="form-control" type="text">${ html }</select>
                        </div>
                        <div class="form-group">
                          <label for="">楼盘名称</label>
                          <select id="dropertyIdBind" name="dropertyId" class="form-control" type="text"></select>
                        </div>
                      </form>
                    </div>`
      break
    default:
      return
  }


  bootbox.confirm({
    title: '提示',
    message: messageHtml,
    buttons: {
      cancel: {
        label: '取消'
      },
      confirm: {
        label: '绑定'
      }
    },
    callback: (result) => {

      if (!result) {
        return
      }

      // 一体机
      if (type === 0) {
        let developersIdBind = $('#developersIdBind').val(),
            dropertyIdBind   = $('#dropertyIdBind').val()

        if (!developersIdBind) {
          layer.msg('请选择开发商', {
            icon: 5
          })

          return false
        }

        if (!dropertyIdBind) {
          layer.msg('请选择楼盘名称', {
            icon: 5
          })

          return false
        }

      }

      // 平板
      if (type === 1) {
        let developersIdBind = $('#developersIdBind').val(),
            dropertyIdBind   = $('#dropertyIdBind').val()

        if (!developersIdBind) {
          layer.msg('请选择开发商', {
            icon: 5
          })

          return false
        }

        if (!dropertyIdBind) {
          layer.msg('请选择楼盘名称', {
            icon: 5
          })

          return false
        }

      }

      // pos
      if (type === 2) {
        let receivablesPeopleId = $('#receivablesPeopleId').val(),
            developersIdBind    = $('#developersIdBind').val(),
            dropertyIdBind      = $('#dropertyIdBind').val()

        if (!receivablesPeopleId) {
          layer.msg('请选择收款方', {
            icon: 5
          })

          return false
        }

        if (!developersIdBind) {
          layer.msg('请选择开发商', {
            icon: 5
          })

          return false
        }

        if (!dropertyIdBind) {
          layer.msg('请选择楼盘名称', {
            icon: 5
          })

          return false
        }

      }

      let loading_modal = layer.msg('提交中...', {
        icon: 16,
        time: 0
      })

      $.ajax({
        headers: header,
        url: base + bindTerminal,
        type: 'POST',
        data: $.extend({
          identifier: "",
          cusId: cusId ? cusId : "",
          developersId: "",
          dropertyId: "",
          receivablesPeopleId: "",
          payChannel: "",
          groupPurchaseType: "",
          contractId: "",
          oneMachineFlowId: ""
        },$('#bindForm').serializeObject())
      })
        .done(function (res) {
          console.log(res)

          if (res.code == 0) {

            layer.msg('绑定成功', {
              icon: 6
            })

            table.bootstrapTable('refresh')

          } else {
            layer.msg('绑定失败', {
              icon: 5
            })
          }

        })
        .fail(function (res) {
          console.log(res)

          layer.msg('绑定失败', {
            icon: 5
          })

        })
        .always(function (res) {

          console.log("complete")

          layer.close(loading_modal)
        })
    }
  })
    .on('shown.bs.modal', () => {
      // 动态加载区域

      if($('#pact').length !== 0){ //初始化合同
        getPactList()
      }

      if($('#receivablesPeopleId').length !== 0){ //初始化收款方
        getReceivablesPeople();
      }

      $('#developersIdBind').selectize();

      $('#developersIdBind').on('change',(e) => {

        e.preventDefault;

        let developersId = $('#developersIdBind').children('option:selected').val();

        getBuild(developersId)

      })


    })

});

// 修改
$(document).on('click', '#table .btn-modify', (e) => {

  storeData.typeName = storeData.typeName || '';

  switch(storeData.typeName.replace(/\s/g, '')) {
    case '一体机':
      storeData.type = 1;
      break;
    case 'POS':
    case 'pos':
    case 'POS机':
    case 'pos机':
      storeData.type = 2;
      break
    case '平板':
      storeData.type = 3;
      break
  }

  console.log(storeData);
  store.set('storeData', storeData);
  window.location = './modify.html'

});